import axios from 'axios'

// 设置请求超时时间、超时重传次数
axios.defaults.timeout = 10 * 1000
;(axios.defaults as any).retry = 3

// 休眠函数，让程序睡一会
const sleep = (min = 1000, rand = 3000) => new Promise(resolve => setTimeout(resolve, (rand * Math.random() + min) >> 0))

// 配置 axios 拦截器
// 请求拦截器：用于控制请求频率
const frequencyLimit = () => {
  axios.interceptors.request.use(config => {
    return new Promise(resolve => {
      sleep().then(() => resolve(config))
    })
  })
}
// 响应拦截器：用于超时自动重传
const retransmission = () => {
  axios.interceptors.response.use(
    response => response,
    err => new Promise((resolve, reject) => {
      (!err || typeof err === 'string') && reject('请求失败的重试次数达到了上限')
      const { config } = err
      config.retryCount ??= 0
      if (config.retryCount >= config.retry) {
        return reject(err.toString())
      }
      config.retryCount += 1
      sleep().then(() => resolve(axios(config)))
    })
  )
}

export { frequencyLimit, retransmission }
